document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('registerForm');
    const unameInput = document.getElementById('uname');
    const pwdInput = document.getElementById('pwd');
    const cpwdInput = document.getElementById('cpwd');
    const submitBtn = document.getElementById('submitBtn');
    const errorMessage = document.getElementById('errorMessage');
    const successMessage = document.getElementById('successMessage');

    // 表单验证规则
    const validationRules = {
        uname: {
            required: true,
            minLength: 3,
            maxLength: 20,
            pattern: /^[a-zA-Z0-9_]+$/
        },
        pwd: {
            required: true,
            minLength: 6,
            maxLength: 20,
            pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]+$/
        }
    };

    // 错误消息
    const errorMessages = {
        uname: {
            required: '请输入用户名',
            minLength: '用户名至少3个字符',
            maxLength: '用户名最多20个字符',
            pattern: '用户名只能包含字母、数字和下划线'
        },
        pwd: {
            required: '请输入密码',
            minLength: '密码至少6个字符',
            maxLength: '密码最多20个字符',
            pattern: '密码必须包含字母和数字'
        },
        cpwd: {
            match: '两次输入的密码不一致'
        }
    };

    // 实时验证函数
    function validateField(input, rules) {
        const value = input.value.trim();
        const fieldName = input.name;
        const formGroup = input.closest('.form-group');
        const errorText = formGroup.querySelector('.error-text');

        // 重置错误状态
        formGroup.classList.remove('error');
        errorText.style.display = 'none';

        // 验证规则
        if (rules.required && !value) {
            showError(formGroup, errorText, errorMessages[fieldName].required);
            return false;
        }

        if (value.length < rules.minLength) {
            showError(formGroup, errorText, errorMessages[fieldName].minLength);
            return false;
        }

        if (value.length > rules.maxLength) {
            showError(formGroup, errorText, errorMessages[fieldName].maxLength);
            return false;
        }

        if (rules.pattern && !rules.pattern.test(value)) {
            showError(formGroup, errorText, errorMessages[fieldName].pattern);
            return false;
        }

        return true;
    }

    // 显示错误信息
    function showError(formGroup, errorText, message) {
        formGroup.classList.add('error');
        errorText.textContent = message;
        errorText.style.display = 'block';
    }

    // 验证确认密码
    function validateConfirmPassword() {
        const formGroup = cpwdInput.closest('.form-group');
        const errorText = formGroup.querySelector('.error-text');

        if (pwdInput.value !== cpwdInput.value) {
            showError(formGroup, errorText, errorMessages.cpwd.match);
            return false;
        }

        formGroup.classList.remove('error');
        errorText.style.display = 'none';
        return true;
    }

    // 添加实时验证事件监听器
    unameInput.addEventListener('input', () => validateField(unameInput, validationRules.uname));
    pwdInput.addEventListener('input', () => validateField(pwdInput, validationRules.pwd));
    cpwdInput.addEventListener('input', validateConfirmPassword);

    // 表单提交处理
    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        // 验证所有字段
        const isUnameValid = validateField(unameInput, validationRules.uname);
        const isPwdValid = validateField(pwdInput, validationRules.pwd);
        const isCpwdValid = validateConfirmPassword();

        if (!isUnameValid || !isPwdValid || !isCpwdValid) {
            return;
        }

        // 禁用提交按钮
        submitBtn.disabled = true;

        try {
            const formData = new FormData(form);
            const params = new URLSearchParams(formData).toString();

            const response = await fetch(`${window.contextPath}/userRegisterServlet?${params}`, {
                method: 'POST'
            });

            const result = await response.json();

            if (result.success) {
                showAlert('注册成功！3秒后跳转到登录页面...');
                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = `${window.contextPath}` + "/toLoginServlet";
                }, 3000);
            } else {
                showAlert(result.message || '注册失败，请稍后重试。');
            }
        } catch (error) {
            console.error('Registration error:', error);
            showAlert('发生错误，请稍后重试。');
        } finally {
            // 重新启用提交按钮
            submitBtn.disabled = false;
        }
    });
});

// 显示弹窗提示
function showAlert(message) {
    // TODO: 实现弹窗提示功能
    alert(message);
}
